package com.yangtao.prototype.system.login.service.impl;

import com.yangtao.framework.cache.CacheFlyweight;
import com.yangtao.framework.cache.CacheManager;
import com.yangtao.framework.common.SystemConstant;
import com.yangtao.framework.service.BaseService;
import com.yangtao.prototype.PrototypeConstant;
import com.yangtao.prototype.system.dao.LogNoteDao;
import com.yangtao.prototype.system.dao.MenuTreeDao;
import com.yangtao.prototype.system.dao.UserDao;
import com.yangtao.prototype.system.domain.LogNote;
import com.yangtao.prototype.system.domain.User;
import com.yangtao.prototype.system.login.service.LoginService;
import com.yangtao.prototype.system.login.service.UserDataCalculator;
import com.yangtao.prototype.system.login.web.LoginModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

/**
 * @author 杨涛
 * @date 2010-03-24
 */
@Service
public class LoginServiceImpl extends BaseService implements LoginService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private LogNoteDao logNoteDao;
	@Autowired
	private MenuTreeDao menuTreeDao;
	@Autowired
	private JedisPool pool;
	@Autowired
	private UserDataCalculator dataCalculator;

	/**
	 * 用户登录
	 * 检查用户姓名，密码，过期时间
	 *
	 * @param model
	 * @return
	 */
	public LoginModel login(LoginModel model) {
		String userCode = model.getUserCode();
		String password = model.getPassword();
		List<User> users = userDao.findByProperty("userCode", userCode);
		// 用户不存在
		if (users == null || users.size() == 0) {
			model.addError("user.not.exsit");
			return model;
		}
		User currentUser = users.get(0);
		// 密码错误
		if (!currentUser.getPassword().equals(password)) {
			model.addError("password.wrong");
			return model;
		}
		// 用户过期
		Date today = new Date();
		if (currentUser.getExpireDate() != null
				&& currentUser.getExpireDate().compareTo(today) < 0) {
			model.addError("user.expired");
			return model;
		}
		//将用户信息保存在缓存中
		Jedis client = pool.getResource();
		String cacheKey = currentUser.cacheUserInfo(client);
		model.setSessionId(cacheKey);
		//增加登录日志
		LogNote logNote = new LogNote();
		logNote.setClientAddress(model.getClientAddr());
		logNote.setClientIp(model.getClientIp());
		logNote.setLogInTime(new Date());
		logNote.setUserId(currentUser.getId());
		logNote.setUserName(currentUser.getUserName());
		logNote.setState(PrototypeConstant.LOGON_STATE);
		logNoteDao.save(logNote);

		//保存登录日志的Id
		client.hset(cacheKey, SystemConstant.LOG_ID, logNote.getId());

		// 加载用户菜单
		model.setMenus(menuTreeDao.findAuhorisedMenu(currentUser.getId()));

		client.hset(currentUser.getId(), "userData_status", "computing");

		//fix-me 将计算用户数据权限的方法设置为异步处理
		//单独开启一个线程计算用户的缓存数据
		calculateUserData(currentUser.getId());

		new Thread(dataCalculator).start();


		//在返回之前返还客户端
		pool.returnResource(client);
		return model;
	}

	/**
	 * 获取在线用户列表
	 *
	 * @param model
	 * @return
	 */
	@Override
	public LoginModel getOnLineUser(LoginModel model) {
		model.setPage(logNoteDao.findOnLineUser(model.getPage()));
		return model;
	}

	/**
	 * 改变用户的登录状态
	 *
	 * @param model
	 * @return
	 */
	@Override
	public LoginModel changeLogNote(LoginModel model) {
		logNoteDao.logOut(model.getLogId());
		return model;
	}

	/**
	 * 查找登录日志
	 *
	 * @param model
	 * @return
	 */
	@Override
	public LoginModel findLogs(LoginModel model) {
		logNoteDao.findPageByExample(model.getPage(), model.getLn());
		return model;
	}

	/**
	 * 模拟计算用户的主数据权限
	 * 计算用户权限
	 *
	 * @param userId
	 */
	public void calculateUserData(String userId) {
		CacheManager cache = CacheFlyweight.getCache();
		Map<String, List<Object>> userData = new HashMap<String, List<Object>>();
		List<Object> customers = new ArrayList<Object>();
		for (int i = 0; i < 10; i++) {
			Customer c = new Customer();
			c.setId(i + "00");
			c.setCode("cst" + i);
			c.setName("客户" + i);
			customers.add(c);
		}
		userData.put("customer", customers);
		cache.put(userId, userData);
	}

}
